package com.zhu.shiro.realm;

import com.zhu.user.model.User;
import com.zhu.user.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by DELL on 2015/12/30.
 */
public class CustomeRealm extends AuthorizingRealm{

    @Autowired
    private UserService userService;

    /**
     * ��ȡ��Ȩ��Ϣ
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Set<String> roleSet = new HashSet<String>();
        roleSet.add("admin");
        info.setRoles(roleSet);

        Set<String> permSet = new HashSet<String>();
        permSet.add("hah");
        info.setStringPermissions(permSet);

        return info;
    }

    /**
     * ��ȡ��¼��Ϣ
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        User user = userService.getUser((String)authenticationToken.getPrincipal());
        if(user == null){
            throw new UnknownAccountException("无该用户名");
        }

        return new SimpleAuthenticationInfo(
                user.getUsername(),
                user.getPassword(),
                user.getSaltSource(),
                getName()
        );
    }

}
